<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\ReportProcessRequest;
use App\Models\V1\NewArrival;
use App\Models\V1\ReportProcess;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;
use Auth;

class ReportProcessesController extends Controller
{
    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.newData.report_process', $data);
    }

    /**
     * 获取生活用品数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $arrival_code = $request->get('arrival_code');

        $from_select = $request->get('from_select');

        if ($from_select == false && empty($arrival_code)) {
            $arrival_code = $this->getArrivalCodes();
        }
        // 获取符合查询条件的班级数据
        $data = $this->getReportProcessList($currentPage, $rows, $arrival_code);
        $formatList = array();

        if (!$data->isEmpty()) {
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['detail'] = $item['detail'];
                    $formatItem['address'] = $item['address'];
                    $formatItem['reception_person'] = $item['reception_person'];
                    $formatItem['handle_procedures'] = $item['handle_procedures'];
                    $formatItem['remark'] = $item['remark'];
                    $formatItem['relate_information'] = $this->formatRelate($item['relate_information'], 1);
                    $formatItem['arrival_code'] = $item['arrival_code'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['msg'] = '加载数据成功';
            }
        } else {
            $count = 0;
            $formatList = [];
            $response['msg'] = '暂无数据';
        }
        $response['code'] = 0;
        $response['count'] = $count;
        $response['data'] = $formatList;
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.report_process_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $arrival_code = $request->input('arrival_code');
                $report = $this->getReportProcessByCode($code, $arrival_code);
                $report['relate_information'] = $this->formatRelate($report['relate_information'], 2);
                $data['report'] = $report;
                return view('v1.form.report_process_item', $data);
        }
    }

    /**
     * 显示迎新换届数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /***
     * 添加关联
     */
    public function addRelation(Request $request)
    {
        $code = $request->get('code');
        $arrival_code = $request->get('arrival_code');
        $data['code'] = $code;
        $data['arrival_code'] = $arrival_code;
        $data['relates'] = $this->getRelateList();
        //获取当前选择的关联
        $report = $this->getReportProcessByCode($code, $arrival_code);
        $relate = $this->formatRelate($report['relate_information'], 3);
        if (empty($relate)) {
            $data['relate'] = 'relate1';
        } else {
            $data['relate'] = $relate;
        }
        return view('v1.newData.report_process_relate', $data);
    }

    public function addRelationData(Request $request)
    {
        $type = $request->get('type');
        $code = $request->get('code');
        $arrival_code = $request->get('arrival_code');
        $response = [
            'rspStatus' => false,
            'rspMsg' => '报到流程[' . $code . '],添加关联失败！',
        ];
        if ($type === 'relate1') {
            $content = [
                'code' => $type,
                'name' => '费用清单'
            ];
        } elseif ($type === 'relate2') {
            $content = [
                'code' => $type,
                'name' => '物品清单'
            ];
        } elseif ($type === 'relate3') {
            $content = [
                'code' => $type,
                'name' => '教材清单'
            ];
        }
        if ($type === 'relate4') {
            $updateData = [
                'relate_information' => '',
            ];
        } else {
            $updateData = [
                'relate_information' => json_encode($content),
            ];
        }
        $rspObj = ReportProcess::where('code', $code)
            ->where('arrival_code', $arrival_code)
            ->update($updateData);
        if ($rspObj) {
            $response['rspStatus'] = true;
            $response['rspMsg'] = '报到流程[' . $code . ']添加关联成功！';
        }
        return $response;
    }

    /***
     * 关联信息数据
     * @return array
     */
    private function getRelateList()
    {
        $process_codes = ['relate1', 'relate2', 'relate3', 'relate4'];
        $process_names = ['费用清单', '物品清单', '教材清单', '不添加'];
        $formatProcess = array();
        for ($i = 0; $i < count($process_codes); $i++) {
            $process = [
                'code' => $process_codes[$i],
                'name' => $process_names[$i],
            ];
            array_push($formatProcess, $process);
        }
        return $formatProcess;
    }

    /**
     * 更新报到流程基本信息(单元格)
     *
     * @param ReportProcessRequest $request
     * @return array
     */
    public function updateCellData(ReportProcessRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '报到流程代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateReportProcess($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '报到流程代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '报到流程[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['detail'] = 'bail|required';
            $rules['address'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '现场报到任务代码不能为空';
            $messages['name.required'] = '现场报到任务名称不能为空';
            $messages['detail.required'] = '具体时间要求不能为空';
            $messages['address.required'] = '地点不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '报到流程[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除班级基本信息
     *
     * @param ReportProcessRequest $request
     * @return array
     */
    public function deleteData(ReportProcessRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '报到流程代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateReportProcess($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '报到流程代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除班级基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '报到流程批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '报到流程批量删除成功！';
            }
        }

        return $response;
    }


    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');
        $arrival_codes = $request->input('arrival_code');
        if ($bBatch) { // 批量删除
            for ($i = 0; $i < count($where); $i++) {
                $code = $where[$i];
                $arrival_code = $arrival_codes[$i];
                $rspObj = ReportProcess::where('code', $code)
                    ->where('arrival_code', $arrival_code)
                    ->delete();
            }
        } else { // 单条删除
            $rspObj = ReportProcess::where('code', $where)
                ->where('arrival_code', $arrival_codes)
                ->delete();
        }

        return $rspObj;
    }


    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request)
    {
        $arrival_code = $this->getArrivalCodes();

        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'detail' => $request->input('detail'),
            'address' => isset($request['address']) ? $request->input('address') : '',
            'reception_person' => isset($request['reception_person']) ? $request->input('reception_person') : '',
            'handle_procedures' => isset($request['handle_procedures']) ? $request->input('handle_procedures') : '',
            'remark' => isset($request['handle_procedures']) ? $request->input('remark') : '',
            'arrival_code' => $arrival_code
        ];
        $rspObj = ReportProcess::updateOrCreate(['code' => $request->input('code')], $insertData);
        return $rspObj;
    }


    /****
     * @param Request $request
     * @param $bCell 是否为单元格修改数据
     * @return mixed
     */
    public function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组

            $updateData = [
                'name' => $request->input('name'),
                'detail' => $request->input('detail'),
                'address' => $request->input('address'),
                'reception_person' => $request->input('reception_person'),
                'handle_procedures' => $request->input('handle_procedures'),
                'remark' => $request->input('remark'),
                'relate_information' => $request->input('relate_information'),
            ];
        }

        $rspObj = ReportProcess::where('code', $where)
            ->where('arrival_code', $arrival_code)
            ->update($updateData);

        return $rspObj;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getReportProcessList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = ReportProcess::orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = ReportProcess::where('arrival_code', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /***
     * 根据code获取报到流程信息
     * @param $code
     * @return mixed
     */
    private function getReportProcessByCode($code, $arrival_code)
    {
        $major = ReportProcess::where('code', $code)->where('arrival_code', $arrival_code)->first();
        return $major;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn', true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateReportProcess(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }


    /***
     * $type  1:表示列表数据   2:查看数据时关联关系的显示什么   3.返回code
     * 格式化相关信息
     * @param $relate_information
     */
    private function formatRelate($relate_information, $type)
    {
        if (empty($relate_information)) {
            if ($type == 1) {
                $result = '添加';
            } elseif ($type == 2) {
                $result = '无';
            } else {
                $result = '';
            }

        } else {
            $content = json_decode($relate_information, true);
            if ($type == 3) {
                $result = $content['code'];
            } else {
                $result = $content['name'];
            }
        }
        return $result;
    }

}
